import React, { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { message } from 'antd';
import { vertifyToken } from '../api/vertifyToken';
import { useUser } from '../store/hooks/useUser';
import { useNotice } from '../store/hooks/useNotice';
//children 传入不具名插槽
const RouterBeforEach = ({ children }) => {
  let location = useLocation();
  let navigate = useNavigate();
  let [authed, setAuthed] = useState(false);
  const { setPermission } = useUser();
  const { uid, username, setUsername, setUid } = useNotice();
  useEffect(() => {
    if (location.pathname == '/login') {
      setAuthed(true);
      return;
    }
    if (!localStorage.getItem('token')) {
      message.success('即将前往登录');
      setAuthed(true);
      navigate('/login');
      return;
    }
    if (location.pathname != '/login') {
      vertifyToken().then((res) => {
        if (res.data.code != 0) {
          message.warning('凭证已过期，请重新登录');
          setAuthed(true);
          navigate('/login');
          return;
        }
        setAuthed(true);
        console.log(res);
        setPermission(res.data.result.user_type == '2');

        setUsername(res.data.result.user_name);
        setUid(res.data.result.user_id);
      });
    }
  }, []);
  return authed ? children : <div></div>;
};

export default RouterBeforEach;
